package com.jay.nio.channel.clazz;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class FileChannelClsLock {
	public static void main(String[] args) throws IOException {
		testLocks();
	}

	public static void testLocks() throws IOException {

		File f = new File("out.txt");
		RandomAccessFile raf;
		try {
			raf = new RandomAccessFile(f, "rw");
			FileChannel fc = raf.getChannel();
			// 不阻塞，立即返回
			// FileLock fl = fc.tryLock();
			// 阻塞，等待锁
			FileLock fl = fc.lock();
			System.out.println("locked");
			if (fl.isValid()) {
				// do something here, use notepad to modify and try to save the
				// // lock file, Fail!
				Thread.sleep(10000);
				fl.release();
				System.out.println("release lock");
			}
			raf.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
}
